import 'dart:io';

import 'package:flutter/material.dart';
import 'package:zhibao_flutter/api/commom/common_view_model.dart';
import 'package:zhibao_flutter/api/mine/mine_view_model.dart';
import 'package:zhibao_flutter/api/user/user_view_model.dart';
import 'package:zhibao_flutter/util/check/regular.dart';
import 'package:zhibao_flutter/util/config/app_config.dart';
import 'package:zhibao_flutter/util/data/q1_data.dart';
import 'package:zhibao_flutter/util/event_bus/avatar_refresh_event.dart';
import 'package:zhibao_flutter/util/float/fram_size.dart';
import 'package:zhibao_flutter/util/func/permission_util.dart';
import 'package:zhibao_flutter/util/func/upload_oss.dart';
import 'package:zhibao_flutter/util/http/http.dart';
import 'package:zhibao_flutter/util/my_theme.dart';
import 'package:zhibao_flutter/util/ui/my_toast.dart';
import 'package:zhibao_flutter/widget/view/hud_view.dart';
import 'package:get/get.dart';
import 'package:image_cropper/image_cropper.dart';

// import 'package:image_picker/image_picker.dart';
enum ImageSource {
  gallery,
  camera,
}

typedef Callback(data);
typedef CallbackVideo(List<String> data);
typedef CallbackPic(List<Q1FileResult> data);

class Q1FileResult {
  final String resultUrl;

  Q1FileResult(this.resultUrl);
}

Future<void> selectPictureDialog(
  context, {
  required CallbackPic callback,
  required bool isIdFileName,
  required bool isCrop,
  required String description,
  bool isTakeAPicture = true,

  /// 只决定样式
  int type = 1,

  /// 传到的文件目录
  required String dir,

  /// 文件名
  String? fileName,
  final int maxCount = 1,
  bool showLoading = false,
}) async {
  if (maxCount < 1) {
    myToast("maxCountError".tr);
    return;
  }
  return PermissionUtil.picturePermission(() {
    return type == 0
        ? showDialog(
            context: context,
            builder: (_) {
              return SelectPictureDialog(
                callback,
                isIdFileName,
                isCrop,
                type,
                fileName,
                description,
                maxCount,
                showLoading,
                isTakeAPicture: isTakeAPicture,
                dir: dir,
                context: context,
              );
            },
          )
        : showModalBottomSheet(
            backgroundColor: Colors.transparent,
            context: context,
            builder: (context) {
              return SelectPictureDialog(
                callback,
                isIdFileName,
                isCrop,
                type,
                fileName,
                description,
                maxCount,
                showLoading,
                isTakeAPicture: isTakeAPicture,
                dir: dir,
                context: context,
              );
            });
  });
}

class SelectPictureDialog extends StatefulWidget {
  final CallbackPic? callback;
  final bool isIdFileName;
  final bool isCrop;
  final int type;
  final bool isTakeAPicture;
  final String dir;
  final String? fileName;
  final String? description;
  final BuildContext context;
  final bool showLoading;

  /// 最多选择数量
  final int maxCount;

  SelectPictureDialog(this.callback, this.isIdFileName, this.isCrop, this.type,
      this.fileName, this.description, this.maxCount, this.showLoading,
      {required this.isTakeAPicture, required this.dir, required this.context});

  @override
  _SelectPictureDialogState createState() => _SelectPictureDialogState();
}

class _SelectPictureDialogState extends State<SelectPictureDialog> {
  @override
  Widget build(BuildContext context) {
    return new GestureDetector(
      child: new Material(
        type: MaterialType.transparency,
        child: new Column(
          mainAxisAlignment: widget.type == 1
              ? MainAxisAlignment.end
              : MainAxisAlignment.center,
          children: [
            widget.type == 1
                ? Expanded(
                    child: InkWell(child: Container(), onTap: () => Get.back()))
                : Container(),
            new Container(
              width: widget.type == 1
                  ? FrameSize.winWidthDynamic(context)
                  : FrameSize.winWidthDynamic(context) - 70,
              padding: EdgeInsets.only(bottom: FrameSize.padBotH()),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: widget.type == 1
                    ? BorderRadius.vertical(top: Radius.circular(8))
                    : BorderRadius.all(
                        Radius.circular(12),
                        // borderRadius: BorderRadius.all(Radius.circular(12)),
                      ),
              ),
              child: new Column(
                children: [
                  'selectFromAlbum'.tr,
                  'takePhoto'.tr,
                  'cancel'.tr,
                ].map((e) {
                  return new InkWell(
                    child: e == "takePhoto".tr && !widget.isTakeAPicture
                        ? Container()
                        : new Container(
                            alignment: Alignment.center,
                            width: widget.type == 1
                                ? FrameSize.winWidthDynamic(context)
                                : FrameSize.winWidthDynamic(context) - 70,
                            padding: EdgeInsets.symmetric(vertical: 15),
                            decoration: e == "cancel".tr
                                ? BoxDecoration(
                                    border: widget.type == 1
                                        ? Border(
                                            top: BorderSide(
                                                color: Color(0xffF2F2F2),
                                                width: 8))
                                        : null)
                                : BoxDecoration(border: MyTheme.mainBorder()),
                            child: new Text(
                              e,
                              style: TextStyle(
                                  color: Color(0xff121212), fontSize: 16),
                            ),
                          ),
                    onTap: () => action(e),
                  );
                }).toList(),
              ),
            )
          ],
        ),
      ),
      onTap: () => Get.back(),
    );
  }

  void action(String e) async {
    Get.back();
    if (e == 'selectFromAlbum'.tr) {
      setImg(ImageSource.gallery);
    } else if (e == 'takePhoto'.tr) {
      setImg(ImageSource.camera);
    }
  }

  void setImg(ImageSource imageSource) async {
    print("${"selectedMethod".tr}${imageSource}");

    List<Q1File> pickResultFileOfNoCrop = await commonViewModel.pickFile(
      widget.context,
      imageSource,
      widget.isCrop ? 1 : widget.maxCount,

      /// Q1Data.sex == 1 mean is check is Female.
      // isCanSelectReadDispose: Q1Data.sex == 1 && widget.isCanSelectReadDispose,
    );

    if (!listNoEmpty(pickResultFileOfNoCrop)) return;

    List<Q1File> pickResultFile;

    print("是否需要裁剪操作::${widget.isCrop}");

    /// 裁剪操作[裁剪说明是头像，只允许上传1个]
    if (widget.isCrop) {
      CroppedFile? croppedFile = await ImageCropper().cropImage(
        sourcePath: pickResultFileOfNoCrop.first.file.path,
        aspectRatio: CropAspectRatio(ratioX: 1, ratioY: 1),
        uiSettings: [
          AndroidUiSettings(
            toolbarTitle: 'imageCropping'.tr,
            toolbarColor: Colors.deepOrange,
            toolbarWidgetColor: Colors.white,
            initAspectRatio: CropAspectRatioPreset.original,
            lockAspectRatio: true,
          ),
          IOSUiSettings(
            title: 'imageCropping'.tr,
            cancelButtonTitle: "cancel".tr,
            doneButtonTitle: "done".tr,
          ),
          WebUiSettings(
            context: widget.context,
          ),
        ],
      );

      if (croppedFile == null) return;
      pickResultFile = [Q1File(File(croppedFile.path))];
    } else {
      pickResultFile = pickResultFileOfNoCrop;
    }

    List<Q1FileResult> returnData = [];

    for (Q1File getFile in pickResultFile) {
      String pathName = UploadOss.getPathName(getFile.file);

      RxString rxValue = "loading".tr.obs;
      if (widget.showLoading) {
        HudView.show(Get.context ?? context, rxValue: rxValue);
      }
      final resultUrl = await commonViewModel.uploadAvatar(Get.context!,
          file: getFile.file, onSendProgress: (int progress, int total) {
            print("上传文件进度：：${progress / total}");
            if (widget.showLoading) {
              rxValue.value = "${"uploading".tr}${(progress / total * 100).toInt()}%";
            }
          });
      if (widget.showLoading) {
        HudView.dismiss();
      }
      print("上传文件成功：：${resultUrl.data}");
      if (resultUrl.data == null) {
        return;
      }
      final valueOfApi =
          await mineViewModel.getSelfInfo(null, Q1Data.loginRspEntity!.token!);
      if (valueOfApi.data == null) {
        return;
      }
      avatarRefreshBus.fire(AvatarRefreshModel());

      returnData.add(Q1FileResult(Q1Data.userInfoEntity?.avatar ?? ""));
    }

    if (widget.callback != null) widget.callback!(returnData);
  }
}
